package com.jiang.demo.springbootmultidatasources.dsconfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryDB2",
        transactionManagerRef = "transactionManagerDB2",
        basePackages = {"com.jiang.demo.springbootmultidatasources.repository.db2"}
)
public class DB2Config {

    @Autowired
    @Qualifier("db2DS")
    private DataSource db2DS;

    @Bean(name = "entityManagerFactoryDB2")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryDB2(EntityManagerFactoryBuilder builder){
        return builder
                .dataSource(db2DS)
                .packages("com.jiang.demo.springbootmultidatasources.entity.db2")
                .persistenceUnit("db2PersistenceUnit")
                .build();
    }

    @Bean(name = "transactionManagerDB2")
    PlatformTransactionManager transactionManagerDB2(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(entityManagerFactoryDB2(builder).getObject());
    }
}
